import tkinter as tk
from tkinter import ttk, scrolledtext
import time
from typing import List, Dict, Any
import json

class DiscussionTab:
    """讨论记录页面"""
    
    def __init__(self, parent_frame):
        self.parent_frame = parent_frame
        self.discussions = []  # 存储所有讨论记录
        self.current_discussion = None  # 当前显示的讨论
        
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI界面"""
        self.parent_frame.columnconfigure(0, weight=1)
        self.parent_frame.rowconfigure(0, weight=1)
        
        # 主分割面板
        self.paned_window = ttk.PanedWindow(self.parent_frame, orient=tk.HORIZONTAL)
        self.paned_window.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 左侧讨论列表
        list_frame = ttk.Frame(self.paned_window, width=200)
        self.paned_window.add(list_frame, weight=0)
        
        # 讨论列表标题
        ttk.Label(list_frame, text="讨论记录", font=('Microsoft YaHei', 12, 'bold')).pack(pady=(10, 5))
        
        # 讨论列表
        self.discussion_listbox = tk.Listbox(list_frame, selectmode=tk.SINGLE)
        self.discussion_listbox.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        self.discussion_listbox.bind('<<ListboxSelect>>', self.on_discussion_select)
        
        # 右侧讨论详情
        detail_frame = ttk.Frame(self.paned_window)
        self.paned_window.add(detail_frame, weight=1)
        
        # 讨论详情标题
        title_frame = ttk.Frame(detail_frame)
        title_frame.pack(fill=tk.X, padx=10, pady=(10, 5))
        
        self.title_label = ttk.Label(title_frame, text="选择讨论记录查看详情", font=('Microsoft YaHei', 14, 'bold'))
        self.title_label.pack()
        
        # 元信息
        self.meta_frame = ttk.Frame(detail_frame)
        self.meta_frame.pack(fill=tk.X, padx=10, pady=(0, 10))
        
        # 讨论内容显示区域
        self.content_text = scrolledtext.ScrolledText(
            detail_frame,
            wrap=tk.WORD,
            font=('Microsoft YaHei', 10),
            padx=10,
            pady=10
        )
        self.content_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        self.content_text.config(state=tk.DISABLED)
        
        # 配置样式
        self.setup_styles()
    
    def setup_styles(self):
        """设置样式"""
        self.content_text.tag_configure("title", font=('Microsoft YaHei', 12, 'bold'), foreground="#2B6DAB")
        self.content_text.tag_configure("timestamp", font=('Microsoft YaHei', 9), foreground="#666666")
        self.content_text.tag_configure("model", font=('Microsoft YaHei', 10, 'bold'), foreground="#1976d2")
        self.content_text.tag_configure("content", font=('Microsoft YaHei', 10))
        self.content_text.tag_configure("round", font=('Microsoft YaHei', 11, 'bold'), foreground="#d63384")
        self.content_text.tag_configure("summary", font=('Microsoft YaHei', 10, 'italic'), foreground="#28a745")
    
    def add_discussion(self, discussion_data: Dict):
        """添加新的讨论记录"""
        self.discussions.append(discussion_data)
        
        # 更新列表
        title = f"{discussion_data['topic']} - {discussion_data['date']}"  # 修改键名
        self.discussion_listbox.insert(tk.END, title)
        
        # 自动选择最新讨论
        self.discussion_listbox.selection_clear(0, tk.END)
        self.discussion_listbox.selection_set(tk.END)
        self.discussion_listbox.see(tk.END)
        self.on_discussion_select()
    
    def display_discussion(self):
        """显示讨论详情"""
        if not self.current_discussion:
            return
        
        self.content_text.config(state=tk.NORMAL)
        self.content_text.delete(1.0, tk.END)
        
        # 显示标题
        self.content_text.insert(tk.END, f"讨论主题: {self.current_discussion['topic']}\n\n", "title")
        
        # 显示元信息
        meta_info = (
            f"开始时间: {self.current_discussion['date']}\n"  # 修改键名
            f"讨论轮数: {self.current_discussion['rounds']}\n"
            f"参与模型: {', '.join(self.current_discussion['participant_models'].keys())}\n"  # 修改键名
            f"调度模型: {self.current_discussion['scheduler_model']}\n\n"  # 修改键名
        )
        self.content_text.insert(tk.END, meta_info, "timestamp")
        
        # 按轮次组织消息
        rounds = {}
        for msg in self.current_discussion.get('messages', []):
            round_num = msg['round']
            if round_num not in rounds:
                rounds[round_num] = []
            rounds[round_num].append(msg)
        
        # 显示讨论内容
        for round_num in sorted(rounds.keys()):
            self.content_text.insert(tk.END, f"=== 第 {round_num} 轮讨论 ===\n\n", "round")
            
            for msg in rounds[round_num]:
                if msg['role'] == 'scheduler':
                    self.content_text.insert(tk.END, f"调度提示 ({msg['model']}): ", "model")
                else:
                    instance_info = f" (实例{msg.get('instance', 1)})" if msg.get('instance') else ""
                    self.content_text.insert(tk.END, f"{msg['model']}{instance_info}: ", "model")
                
                self.content_text.insert(tk.END, f"{msg['content']}\n\n", "content")
        
        # 显示总结
        if 'summary' in self.current_discussion:
            self.content_text.insert(tk.END, "=== 讨论总结 ===\n\n", "round")
            self.content_text.insert(tk.END, self.current_discussion['summary'], "summary")
        
        self.content_text.config(state=tk.DISABLED)
    
    def update_discussion(self, discussion_data: Dict):
        """更新讨论记录"""
        # 查找并更新现有的讨论记录
        for i, disc in enumerate(self.discussions):
            if disc['id'] == discussion_data['id']:
                self.discussions[i] = discussion_data
                self.current_discussion = discussion_data
                self.display_discussion()
                break
    
    def on_discussion_select(self, event=None):
        """选择讨论记录事件"""
        selection = self.discussion_listbox.curselection()
        if not selection:
            return
        
        index = selection[0]
        self.current_discussion = self.discussions[index]
        self.display_discussion()
    
    def clear(self):
        """清空讨论记录"""
        self.discussions.clear()
        self.discussion_listbox.delete(0, tk.END)
        self.content_text.config(state=tk.NORMAL)
        self.content_text.delete(1.0, tk.END)
        self.content_text.config(state=tk.DISABLED)
        self.title_label.config(text="选择讨论记录查看详情")
        
        # 清空元信息
        for widget in self.meta_frame.winfo_children():
            widget.destroy()